package org.cweili.rayminder.servlet

import groovy.util.logging.Commons

import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 *
 * @author Cweili
 * @version 13-9-11 下午10:54
 *
 */
@Commons
class CharacterEncodingFilter implements Filter {

	static String encoding
	static boolean forceEncoding = false

	@Override
	void init(FilterConfig filterConfig) throws ServletException {
		if (!this.encoding) {
			this.encoding = filterConfig.getInitParameter('encoding') ?: 'UTF-8'
			this.forceEncoding = filterConfig.getInitParameter('forceEncoding') == "true"
		}
	}

	@Override
	void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

		def request = (HttpServletRequest) servletRequest
		def response = (HttpServletResponse) servletResponse
		if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		try {
			filterChain.doFilter(request, response);
		} catch (Exception e) {
			log.error(e, e)
		}
	}

	@Override
	void destroy() {

	}
}
